package handlers

import (
	"sysu-giep/internal/config"
	"sysu-giep/internal/database"
	"sysu-giep/internal/service"
	"sysu-giep/pkg/logger"
	"sysu-giep/pkg/response"

	"github.com/gin-gonic/gin"
)

// SendEmailRequest 发送邮件请求
type SendEmailRequest struct {
	Email   string `json:"email" binding:"required,email"`
	Type    *int   `json:"type" binding:"required,min=0,max=3"`
	Message string `json:"message,omitempty"`
}

// ValidateEmailCodeRequest 验证邮箱验证码请求
type ValidateEmailCodeRequest struct {
	Email string `json:"email" binding:"required,email"`
	Code  string `json:"code" binding:"required,len=6"`
}

// SendEmail 发送邮件
// @Summary 发送邮件
// @Description 发送邮件接口，支持验证码、通知等类型
// @Tags 邮箱
// @Accept json
// @Produce json
// @Param request body SendEmailRequest true "发送邮件信息"
// @Success 200 {object} response.Response{data=map[string]interface{}}
// @Failure 400 {object} response.Response
// @Router /email/send [post]
func SendEmail(c *gin.Context) {
	var req SendEmailRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "请求参数错误: "+err.Error())
		return
	}

	// 验证邮箱格式
	if req.Email == "" {
		response.BadRequest(c, "邮箱地址不能为空")
		return
	}

	// 验证邮件类型
	if req.Type == nil || *req.Type < 0 || *req.Type > 3 {
		response.BadRequest(c, "邮件类型无效，支持的类型：0-验证码，1-评论通知，2-私信通知，3-回复通知")
		return
	}

	// 获取配置
	cfg := c.MustGet("config").(*config.Config)

	// 获取Redis客户端
	redisClient := database.GetRedisClient()

	// 创建邮箱服务
	emailService := service.NewEmailService(&cfg.Email, redisClient)

	// 创建发送邮件请求
	sendReq := &service.SendEmailRequest{
		To:      req.Email,
		Type:    service.EmailType(*req.Type),
		Message: req.Message,
	}

	// 发送邮件
	result, err := emailService.SendEmail(sendReq)
	if err != nil {
		logger.ErrorLog("发送邮件失败", logger.Error(err))
		response.InternalServerError(c, "发送邮件失败: "+err.Error())
		return
	}

	responseData := gin.H{
		"success": result.Success,
		"message": result.Message,
	}

	// 如果是验证码邮件，在开发环境下返回验证码用于测试
	if *req.Type == int(service.EmailTypeValidate) && cfg.App.Mode == "debug" {
		responseData["vcode"] = result.VCode
	}

	response.Success(c, responseData)
}

// ValidateEmailCode 验证邮箱验证码
// @Summary 验证邮箱验证码
// @Description 验证邮箱验证码接口
// @Tags 邮箱
// @Accept json
// @Produce json
// @Param request body ValidateEmailCodeRequest true "验证码信息"
// @Success 200 {object} response.Response
// @Failure 400 {object} response.Response
// @Router /email/validate [post]
func ValidateEmailCode(c *gin.Context) {
	var req ValidateEmailCodeRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "请求参数错误: "+err.Error())
		return
	}

	// 验证邮箱格式
	if req.Email == "" {
		response.BadRequest(c, "邮箱地址不能为空")
		return
	}

	// 验证验证码格式
	if len(req.Code) != 6 {
		response.BadRequest(c, "验证码必须是6位数字")
		return
	}

	// 获取配置
	cfg := c.MustGet("config").(*config.Config)

	// 获取Redis客户端
	redisClient := database.GetRedisClient()

	// 创建邮箱服务
	emailService := service.NewEmailService(&cfg.Email, redisClient)

	// 验证验证码
	err := emailService.ValidateEmailCode(req.Email, req.Code)
	if err != nil {
		logger.ErrorLog("验证邮箱验证码失败", logger.Error(err))
		response.BadRequest(c, err.Error())
		return
	}

	response.SuccessWithMessage(c, "验证码验证成功", nil)
}
